package com.google.code.customercare.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.util.StrutsTypeConverter;

import com.opensymphony.xwork2.conversion.TypeConversionException;



public class DateConverter extends StrutsTypeConverter  {
	
	private static Logger log = Logger.getLogger(DateConverter.class);

	/**
	 * Convert string to date
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) throws TypeConversionException{
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");		

        if (values == null || values.length == 0 || values[0].trim().length() == 0) {
            return null;
        }
		
		Date date = null;
		try {
			date = sdf.parse(values[0]);
		} catch (ParseException e) {
			log.error("Error", e);
		} catch (TypeConversionException e){
			log.error("Error", e);
		}
		return date;
	}
	
	/**
	 * Convert date object to string
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertToString(java.util.Map, java.lang.Object)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public String convertToString(Map context, Object o) throws TypeConversionException{
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		String res = null;
		 if (o != null && o instanceof Date) {
			 res = sdf.format(o);
	            return res;
	     } else {
	            return null;
	     }
	}
}






